package cn.hxh.page.controller;

import cn.hxh.page.pojo.baiDuPageInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/10/3 23:18
 */

@Controller
public class PageController {

    @RequestMapping("/index")
    public String toIndex(){
        return "index";
    }



    //解析百度的数据API
    @ResponseBody
    @RequestMapping("/parseBaiDu")
    public List<baiDuPageInfo> parseBaiDu(@RequestParam("wd")String wd){
        JSONArray jsonArray = null;
        List<baiDuPageInfo> baiDuPageInfoList = new ArrayList<baiDuPageInfo>();
        String substring = "";
        try {
            URL url = new URL("https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=32820,32617,1439,32705,32230,7517,7605&wd="+wd+"&req=2&bs=bd&csor=1&cb=jQuery1102009418700009075054_1601738372871&_=1601738372877");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //获取流对象
            InputStream inputStream = urlConnection.getInputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            StringBuffer str = new StringBuffer();
            while ((len = inputStream.read(bytes))!= -1){
                str.append(new String(bytes,0,len));
            }
            String string = str.toString();
            int is = string.indexOf("(");
            String parseStr =  str.substring(is+1, string.lastIndexOf(")"));
            JSONObject jsonObject = JSON.parseObject(parseStr);
            jsonArray = jsonObject.getJSONArray("g");
            for (int i = 0; i < jsonArray.size(); i++) {
                baiDuPageInfo info = new baiDuPageInfo();
                Map map = (Map) jsonArray.get(i);
                String type = (String) map.get("type");
                String sa = (String) map.get("sa");
                String q = (String) map.get("q");
                info.setQ(q);
                info.setType(type);
                info.setSa(sa);
                baiDuPageInfoList.add(info);
            }
        } catch (Exception e) {
            System.out.println("解析失败");
        }

        return baiDuPageInfoList;
    }


}
